package cc.ok200.api.controller;

import cc.ok200.api.common.ApiException;
import cc.ok200.api.common.ApiRequest;
import cc.ok200.api.common.ApiResponse;
import cc.ok200.api.entity.User;
import cc.ok200.api.entity.UserDevice;
import cc.ok200.api.entity.UserPlugin;
import cc.ok200.api.entity.UserToken;
import cc.ok200.api.repository.UserDao;
import cc.ok200.api.repository.UserDeviceDao;
import cc.ok200.api.repository.UserPluginDao;
import cc.ok200.api.repository.UserTokenDao;
import cc.ok200.api.websocket.WebSocketServer;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.ArrayList;

/**
 * 用户相关接口控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {
    
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    private UserDao userDao;
    
    @Autowired
    private UserDeviceDao userDeviceDao;

    @Autowired
    private UserPluginDao userPluginDao;
    
    @Autowired
    private UserTokenDao userTokenDao;

    /**
     * 获取用户余额
     * 
     * @param request HTTP请求
     * @return 用户余额信息
     */
    @GetMapping("/balance")
    public ApiResponse getBalance(HttpServletRequest request) throws ApiException {
        logger.info("获取用户余额请求");
        
        // 构造API请求对象
        ApiRequest req = new ApiRequest(request, null);
        
        // 获取当前登录用户
        User user = req.getUser();
        
        // 创建响应对象
        ApiResponse response = new ApiResponse();
        response.put("balance", user.balance);
        return response;
    }

    /**
     * 获取用户插件列表
     * 
     * @param request HTTP请求
     * @return 插件列表
     */
    @GetMapping("/plugin/list")
    public ApiResponse getPluginList(HttpServletRequest request) throws ApiException {
        logger.info("获取插件列表请求");
        
        // 构造API请求对象
        ApiRequest req = new ApiRequest(request, null);
        
        // 获取当前登录用户
        User user = req.getUser();
        
        // 查询用户的插件列表
        List<UserPlugin> plugins = userPluginDao.findByUserId(user.id);

        System.out.println(JSON.toJSONString(plugins));
        
        // 创建响应对象
        ApiResponse response = new ApiResponse();
        response.put("plugins", plugins);
        return response;
    }
    
    /**
     * 获取用户设备列表
     * 
     * @param request HTTP请求
     * @return 设备列表
     */
    @GetMapping("/device/list")
    public ApiResponse getDeviceList(HttpServletRequest request) throws ApiException {
        logger.info("获取设备列表请求");
        
        // 构造API请求对象
        ApiRequest req = new ApiRequest(request, null);
        
        // 获取当前登录用户
        User user = req.getUser();
        
        // 查询用户的设备列表
        List<UserDevice> devices = userDeviceDao.findByUserId(user.id);
        
        // 创建包含在线状态的设备列表
        List<Map<String, Object>> devicesWithOnlineStatus = new ArrayList<>();
        
        // 处理每个设备，添加online字段
        for (UserDevice device : devices) {
            Map<String, Object> deviceMap = new HashMap<>();
            // 复制设备信息到Map
            deviceMap.put("id", device.id);
            deviceMap.put("userId", device.userId);
            deviceMap.put("name", device.name);
            deviceMap.put("alias", device.alias);
            deviceMap.put("width", device.width);
            deviceMap.put("height", device.height);
            deviceMap.put("brand", device.brand);
            deviceMap.put("model", device.model);
            deviceMap.put("osVersion", device.osVersion);
            deviceMap.put("createTime", device.createTime);
            
            // 添加online状态
            deviceMap.put("online", WebSocketServer.isOnline(device.id));
            
            devicesWithOnlineStatus.add(deviceMap);
        }
        
        // 创建响应对象
        ApiResponse response = new ApiResponse();
        response.put("devices", devicesWithOnlineStatus);
        return response;
    }
    
    /**
     * 获取特定插件信息
     *
     * @param request HTTP请求
     * @param id 插件ID
     * @return 插件信息
     */
    @GetMapping("/plugin")
    public ApiResponse getPlugin(HttpServletRequest request, @RequestParam String id) throws ApiException {
        logger.info("获取插件信息请求，插件ID: " + id);
        
        // 构造API请求对象
        ApiRequest req = new ApiRequest(request, null);
        
        // 获取当前登录用户
        User user = req.getUser();
        
        // 查询特定插件
        UserPlugin plugin = userPluginDao.findById(id).orElse(null);
        
        // 检查插件是否存在
        if (plugin == null) {
            throw new ApiException("插件不存在");
        }
        
        // 检查插件是否属于当前用户
        if (!plugin.userId.equals(user.id)) {
            throw new ApiException("无权访问此插件");
        }
        
        // 创建响应对象
        ApiResponse response = new ApiResponse();
        response.put("plugin", plugin);
        return response;
    }
    
    /**
     * 用户登录接口
     * 
     * @param request HTTP请求
     * @param params 请求参数
     * @return 登录结果
     */
    @GetMapping("/login")
    public ApiResponse login(HttpServletRequest request, @RequestParam Map<String, Object> params) throws ApiException {
        logger.info("用户登录请求");
        
        // 构造API请求对象
        ApiRequest req = new ApiRequest(request, params);
        
        // 获取请求参数
        String mobile = req.getString("mobile");
        String password = req.getString("password");
        
        // 查询用户
        User user = userDao.findByMobileAndPassword(mobile, password);
        if (user == null) {
            throw new ApiException("用户名或密码错误");
        }
        
        // 创建新令牌
        UserToken token = new UserToken();
        token.id = UUID.randomUUID().toString().replace("-", "");
        token.userId = user.id;
        token.createTime = new Date();
        userTokenDao.save(token);

        // 构建响应，只返回token
        ApiResponse response = new ApiResponse();
        response.put("token", token.id);
        
        return response;
    }
    
    /**
     * 设备登录接口
     * 
     * @param request HTTP请求
     * @param body 请求体数据
     * @return 登录结果
     */
    @PostMapping("/device/login")
    public ApiResponse deviceLogin(HttpServletRequest request, @RequestBody Map<String, Object> body) throws ApiException {
        
        // 构造API请求对象
        ApiRequest req = new ApiRequest(request, body);
        
        // 获取请求参数
        String mobile = req.getString("mobile"); // 账号
        String password = req.getString("password"); // 密码
        String name = req.getString("name", "我的手机"); // 手机昵称
        String uuid = req.getString("uuid"); // 设备唯一标识
        int width = req.getInt("width"); // 屏幕宽度
        int height = req.getInt("height"); // 屏幕高度
        String brand = req.getString("brand"); // 品牌，如：xiaomi
        String model = req.getString("model"); // 型号，如：mi 8
        int osVersion = req.getInt("osVersion"); // 安卓系统版本，如：29

        // 查询用户
        User user = userDao.findByMobileAndPassword(mobile, password);
        if (user == null) {
            throw new ApiException("密码错误");
        }

        // 查询设备
        UserDevice userDevice = userDeviceDao.findById(uuid).orElse(null);
        if (userDevice == null) {
            userDevice = new UserDevice();
            userDevice.id = uuid;
        }
        userDevice.userId = user.id;
        userDevice.name = name;
        userDevice.width = width;
        userDevice.height = height;
        userDevice.brand = brand;
        userDevice.model = model;
        userDevice.osVersion = osVersion;
        userDevice.createTime = new Date();
        userDeviceDao.save(userDevice);
        
        // 查找用户最新令牌，如果不存在，则创建新令牌
        UserToken token = userTokenDao.findTopByUserIdOrderByCreateTimeDesc(user.id);
        if (token == null) {
            token = new UserToken();
            token.id = UUID.randomUUID().toString().replace("-", "");
            token.userId = user.id;
            token.createTime = new Date();
            userTokenDao.save(token);
        }

        ApiResponse response = new ApiResponse();
        response.put("token", token.id);
        return response;
    }
    
    /**
     * 更改设备别名
     * 
     * @param request HTTP请求
     * @param body 请求体数据
     * @return 更新结果
     */
    @PostMapping("/device/alias/change")
    public ApiResponse changeDeviceAlias(HttpServletRequest request, @RequestBody Map<String, Object> body) throws ApiException {
        logger.info("更改设备别名请求");
        
        // 构造API请求对象
        ApiRequest req = new ApiRequest(request, body);
        
        // 获取当前登录用户
        User user = req.getUser();
        
        // 获取请求参数
        String id = req.getString("id");
        String newAlias = req.getString("newAlias");
        
        // 查询设备
        UserDevice device = userDeviceDao.findById(id).orElse(null);
        
        // 检查设备是否存在
        if (device == null) {
            throw new ApiException("设备不存在");
        }
        
        // 检查设备是否属于当前用户
        if (!device.userId.equals(user.id)) {
            throw new ApiException("无权修改此设备");
        }
        
        // 更新设备别名
        device.alias = newAlias;
        userDeviceDao.save(device);
        
        // 创建响应对象
        ApiResponse response = new ApiResponse();
        response.put("success", true);
        return response;
    }
    
    /**
     * 解绑设备
     * 
     * @param request HTTP请求
     * @param body 请求体数据
     * @return 解绑结果
     */
    @PostMapping("/device/unbind")
    public ApiResponse unbindDevice(HttpServletRequest request, @RequestBody Map<String, Object> body) throws ApiException {
        logger.info("解绑设备请求");
        
        // 构造API请求对象
        ApiRequest req = new ApiRequest(request, body);
        
        // 获取当前登录用户
        User user = req.getUser();
        
        // 获取请求参数
        String id = req.getString("id");
        
        // 查询设备
        UserDevice device = userDeviceDao.findById(id).orElse(null);
        
        // 检查设备是否存在
        if (device == null) {
            throw new ApiException("设备不存在");
        }
        
        // 检查设备是否属于当前用户
        if (!device.userId.equals(user.id)) {
            throw new ApiException("无权解绑此设备");
        }
        
        // 删除设备
        userDeviceDao.delete(device);
        
        // 创建响应对象
        ApiResponse response = new ApiResponse();
        response.put("success", true);
        return response;
    }
} 